import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/core/repository/default_api.dart';

class ApplicationDetailLogic extends GetxController {
  final _api = DefaultApi();

  late int applicationId;
  late int applicantId;
  late String userName;
  late String groupName;
  late String groupCode;
  late String time;
  late String approvalState;
  late String joinTypeText;
  late bool canApprove;
  late bool isCreator;

  final isProcessing = false.obs;

  @override
  void onInit() {
    super.onInit();
    // 获取传递的参数
    final args = Get.arguments as Map<String, dynamic>?;
    applicationId = args?['applicationId'] ?? 0;
    applicantId = args?['applicantId'] ?? 0;
    userName = args?['userName'] ?? '';
    groupName = args?['groupName'] ?? '';
    groupCode = args?['groupCode'] ?? '';
    time = args?['time'] ?? '';
    approvalState = args?['approvalState'] ?? '1';
    joinTypeText = args?['joinTypeText'] ?? '申请加入';
    canApprove = args?['canApprove'] ?? false;
    isCreator = args?['isCreator'] ?? false;
  }

  /// 拒绝申请
  void reject() {
    // 根据场景生成不同的提示文案
    String content;
    if (isCreator && joinTypeText == '申请加入') {
      // 我是群主，别人申请加入我的群
      content = '确定要拒绝 $userName 加入"$groupName"群组的申请吗？';
    } else if (!isCreator && joinTypeText == '邀请加入') {
      // 别人邀请我加入群组
      content = '确定要拒绝 $userName 邀请你加入"$groupName"群组吗？';
    } else {
      content = '确定要拒绝吗？';
    }

    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.grey[900],
        title: const Text(
          '确认拒绝',
          style: TextStyle(color: Colors.white),
        ),
        content: Text(
          content,
          style: TextStyle(color: Colors.grey[400]),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Get.back(); // 关闭对话框
              await _processApproval('3'); // 3 表示拒绝
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
            ),
            child: const Text(
              '拒绝',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  /// 同意申请
  void accept() {
    // 根据场景生成不同的提示文案
    String content;
    if (isCreator && joinTypeText == '申请加入') {
      // 我是群主，别人申请加入我的群
      content = '确认同意 $userName 加入"$groupName"群组吗？';
    } else if (!isCreator && joinTypeText == '邀请加入') {
      // 别人邀请我加入群组
      content = '确认同意 $userName 邀请你加入"$groupName"群组吗？';
    } else {
      content = '确认同意吗？';
    }

    Get.dialog(
      AlertDialog(
        backgroundColor: Colors.grey[900],
        title: const Text(
          '确认同意',
          style: TextStyle(color: Colors.white),
        ),
        content: Text(
          content,
          style: TextStyle(color: Colors.grey[400]),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Get.back(); // 关闭对话框
              await _processApproval('2'); // 2 表示同意
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFFF46425),
            ),
            child: const Text(
              '同意',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  /// 处理审批
  Future<void> _processApproval(String approvalState) async {
    if (isProcessing.value) return;

    try {
      isProcessing.value = true;

      final response = await _api.approvalPost(
        id: applicationId,
        applicantId: applicantId,
        groupCode: groupCode,
        approvalState: approvalState,
        isShowLoading: true,
      );

      if (response != null && response['code'] == 200) {
        Toast.show(approvalState == '2' ? '已同意' : '已拒绝');
        Get.back(result: true); // 返回消息列表并刷新
      } else {
        Toast.show(response?['msg'] ?? '操作失败');
      }
    } catch (e) {
      print('处理审批失败: $e');
      Toast.show('操作失败: $e');
    } finally {
      isProcessing.value = false;
    }
  }
}
